﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using NPOI.HSSF.UserModel;
using System.IO;
using System.Data;
using System.Diagnostics;

namespace DoubleH.Utility.IO
{
    class CsvTool : FCNS.Data.Interface.IFileIO
    {
        private string fileName = null; //文件名

        public DataTable ImportFile(string file, string[] args)
        {
            if (string.IsNullOrEmpty(fileName))
                return null;

            this.fileName = file;
            string sheetName = args.Length > 0 ? args[0] : string.Empty;
            return TxtToDataTable();
        }

        public void ExportData(string file, DataTable dataTable)
        {
        }

        private DataTable TxtToDataTable()
        {
            DataTable data = new DataTable();
            try
            {
                StreamReader reader = new StreamReader(fileName, Encoding.UTF8);
                string line = reader.ReadLine();
                if (string.IsNullOrEmpty(line))
                    return null;

                string[] columns = line.Split(',');
                for (int i = 0; i < columns.Length; i++)
                {
                    DataColumn column = new DataColumn(columns[i]);
                    data.Columns.Add(column);
                }

                line = reader.ReadLine();
                while (!string.IsNullOrEmpty(line))
                {
                    DataRow dataRow = data.NewRow();
                    columns = line.Split(',');
                    for (int i = 0; i < columns.Length; i++)
                        dataRow[i] = columns[i];

                    data.Rows.Add(dataRow);
                    line = reader.ReadLine();
                }

                return data;
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception: " + ex.Message);
                return null;
            }
        }
    }
}